package com.wz.wiki.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wz.wiki.entity.pojo.Ebook;
import com.wz.wiki.entity.pojo.EbookExample;
import com.wz.wiki.entity.req.EbookQueryReq;
import com.wz.wiki.entity.req.EbookSaveReq;
import com.wz.wiki.entity.resp.EbookQueryResp;
import com.wz.wiki.entity.resp.PageResp;
import com.wz.wiki.mapper.EbookMapper;
import com.wz.wiki.service.EbookService;
import com.wz.wiki.utils.CopyBeanUtils;
import com.wz.wiki.utils.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName TestService.java
 * @create 2023年06月28日 下午2:53
 * @Description 电子书业务层接口实现类
 * @Version V1.0
 */
@Service
public class EbookServiceImpl implements EbookService {

    @Resource
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    @Override
    public PageResp<EbookQueryResp> selectList(EbookQueryReq req) {
        EbookExample ebookExample = new EbookExample();
        // 创建查询条件
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())){
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if (!ObjectUtils.isEmpty(req.getCategoryId2())){
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ebook> ebooks = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> ebookPageInfo = new PageInfo<>(ebooks);
        System.out.println("总行数：" + ebookPageInfo.getTotal());

        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(ebookPageInfo.getTotal());
        pageResp.setList(CopyBeanUtils.copyList(ebooks, EbookQueryResp.class));

        return pageResp;
    }

    @Override
    public void save(EbookSaveReq req) {

        Long id = req.getId();
        Ebook ebook = CopyBeanUtils.copy(req, Ebook.class);
        if (id == null) {
            // 新增
            id = snowFlake.nextId();
            ebook.setId(id);
            ebookMapper.insert(ebook);
        }else {
            // 更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    @Override
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
